<template>
  <div>
    <div class="search-bar">
      <span class="label">统计时间</span>
      <el-date-picker
        size="mini"
        v-model="timeVal"
        type="daterange"
        :format="dateForm()"
        :value-format="dateForm()"
        placeholder="选择日期"
        :clearable="false"
      >
      </el-date-picker>
      <el-button class="search-btn" size="mini" @click="toSearch"
        >查询</el-button
      >
      <el-button class="search-btn" size="mini" @click="toExport"
        >导出Excel</el-button
      >
    </div>
    <el-table
      id="table"
      ref="table"
      :data="tableData"
      :span-method="arraySpanMethod"
      border
      style="width: 100%"
      :height="tableHeight"
      :row-style="rowStyle"
      class="el-table"
      :cell-style="rowStyle"
      :header-cell-style="rowStyle"
    >
      <el-table-column prop="index" label="序号" width="50"> </el-table-column>
      <el-table-column prop="deptName" label="部门"> </el-table-column>
      <el-table-column prop="count" label="机组"> </el-table-column>
      <el-table-column prop="hours0" label="标准总台时数(H0)">
      </el-table-column>
      <el-table-column prop="hours1" label="故障检修时间(H1)">
      </el-table-column>
      <el-table-column prop="hours2" label="计划检修时间(H2)">
      </el-table-column>
      <el-table-column prop="hours3" label="正常维护时间(H3)">
      </el-table-column>
      <el-table-column prop="hours4" label="大修时间(H4)"> </el-table-column>
      <el-table-column prop="hours5" label="总检修时间(H5)"> </el-table-column>
    </el-table>
  </div>
</template>
<script>
import { unitOverhaulTime } from "@/api/operationManagement/runStatistical.js";
export default {
  data() {
    return {
      timeVal: [],
      tableData: [],
      tableHeight: 0,
    };
  },
  created() {
    this.init();
  },
  mounted() {
    this.adjustSize();
    window.addEventListener("resize", this.adjustSize);
  },
  methods: {
    adjustSize() {
      this.$nextTick(() => {
        this.tableHeight =
          window.innerHeight - this.$refs.table.$el.offsetTop - 200;
        //window.innerHeight:浏览器的可用高度
        //this.$refs.table.$el.offsetTop：表格距离浏览器的高度
        //后面的50：根据需求空出的高度，自行调整
      });
    },
    //获取当月第一天或最后一天的日期
    getFirstOrLastDay(flag) {
      let y = new Date().getFullYear(); //获取年份
      let m = new Date().getMonth() + 1; //获取月份
      let d = new Date(y, m, flag).getDate();
      m = m < 10 ? "0" + m : m; //月份补 0
      d = d < 10 ? "0" + d : d; //日数补 0
      return [y, m, d].join("-");
    },
    init() {
      let nowFirst = this.getFirstOrLastDay(1);
      let nowLast = this.getFirstOrLastDay(0);
      this.timeVal = [nowFirst, nowLast];
      this.toSearch();
    },
    // 设置行颜色
    rowStyle({ row }) {
      let styleJson = {
        borderColor: "#000",
      };
      if (row.purple) {
        styleJson.background = "rgb(184,183,218)"; // 紫色
        return styleJson;
      } else {
        return styleJson;
      }
    },
    // 查询
    async toSearch() {
      let obj = {
        beginDay: this.timeVal[0],
        endDay: this.timeVal[1],
      };
      await unitOverhaulTime(obj).then((res) => {
        if (res.code == 200) {
          this.tableData = [];
          res.data.forEach((item, index) => {
            let obj = {
              mergeLength: 1,
              index: this.convertToChinaNum(index + 1),
              purple: true,
              deptName: item.deptName,
              count: item.qty,
              hours0: item.h0,
              hours1: item.h1,
              hours2: item.h2,
              hours3: item.h3,
              hours4: item.h4,
              hours5: item.h5,
            };
            this.tableData.push(obj);
            if (item.det) {
              item.det.forEach((detItem, detIndex) => {
                if (detItem.det) {
                  detItem.det.forEach((inItem, inIndex) => {
                    let inObj = {
                      hours0: inItem.h0,
                      hours1: inItem.h1,
                      hours2: inItem.h2,
                      hours3: inItem.h3,
                      hours4: inItem.h4,
                      hours5: inItem.h5,
                    };
                    if (inIndex == 0) {
                      inObj.mergeLength = detItem.det.length;
                      inObj.index = detIndex + 1;
                      inObj.deptName = detItem.deptManageName;
                    }
                    if (inItem.equipmentId) {
                      inObj.count = inItem.equipmentName;
                    } else {
                      inObj.deptName = "合计";
                      inObj.mergeLength = -1;
                    }
                    this.tableData.push(inObj);
                  });
                }
              });
            }
          });
        }
      });
    },
    // 合并表格
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        if (row.mergeLength == -1) {
          return [0, 0];
        } else if (row.mergeLength) {
          return [row.mergeLength, 1];
        } else {
          return [0, 0];
        }
      }
      if (columnIndex === 1) {
        if (row.mergeLength) {
          if (row.mergeLength == 1) {
            return [1, 1];
          } else {
            return [row.mergeLength - 1, 1];
          }
        } else {
          return [0, 0];
        }
      }
    },
    // 导出Excel
    toExport() {
      let table = document.getElementById("table");
      let excelContent = table.innerHTML;
      let excelFile =
        "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:" +
        "excel" +
        "' xmlns='http://www.w3.org/TR/REC-html40'>";
      excelFile += "<>";
      excelFile += "<!--[if gte mso 9]>";
      excelFile += "<xml>";
      excelFile += "<x:ExcelWorkbook>";
      excelFile += "<x:ExcelWorksheets>";
      excelFile += "<x:ExcelWorksheet>";
      excelFile += "<x:Name>";
      excelFile += "{worksheet}";
      excelFile += "</x:Name>";
      excelFile += "<x:WorksheetOptions>";
      excelFile += "<x:DisplayGridlines/>";
      excelFile += "</x:WorksheetOptions>";
      excelFile += "</x:ExcelWorksheet>";
      excelFile += "</x:ExcelWorksheets>";
      excelFile += "</x:ExcelWorkbook>";
      excelFile += "</xml>";
      excelFile += "<![endif]-->";
      excelFile += "</head>";
      excelFile += "<body>";
      excelFile += excelContent;
      excelFile += "</body>";
      excelFile += "</html>";
      let base64data = "base64," + this.base64(excelFile);
      let fileName = "机组检修台时"; //下载的文件名称
      let prefix = "data:application/vnd.ms-excel;" + base64data;
      let a = document.createElement("a"); //创建a标签
      a.setAttribute("href", prefix);
      a.setAttribute("download", fileName);
      a.setAttribute("target", "_blank"); //打开一个新的窗口
      a.setAttribute("id", "downLoad");
      if (document.getElementById("downLoad")) {
        document.body.removeChild(document.getElementById("downLoad"));
      }
      document.body.appendChild(a);
      a.click();
    },
    base64(content) {
      return window.btoa(unescape(encodeURIComponent(content)));
    },
    //日期数据处理
    dateForm() {
      return "yyyy-MM-dd";
    },
    //将数字（整数）转为汉字，从零到一亿亿
    convertToChinaNum(num) {
      let arr1 = new Array(
        "零",
        "一",
        "二",
        "三",
        "四",
        "五",
        "六",
        "七",
        "八",
        "九"
      );
      let arr2 = new Array(
        "",
        "十",
        "百",
        "千",
        "万",
        "十",
        "百",
        "千",
        "亿",
        "十",
        "百",
        "千",
        "万",
        "十",
        "百",
        "千",
        "亿"
      ); //可继续追加更高位转换值
      if (!num || isNaN(num)) {
        return "零";
      }
      let english = num.toString().split("");
      let result = "";
      for (let i = 0; i < english.length; i++) {
        let des_i = english.length - 1 - i; //倒序排列设值
        result = arr2[i] + result;
        let arr1_index = english[des_i];
        result = arr1[arr1_index] + result;
      }
      //将【零千、零百】换成【零】 【十零】换成【十】
      result = result.replace(/零(千|百|十)/g, "零").replace(/十零/g, "十");
      //合并中间多个零为一个零
      result = result.replace(/零+/g, "零");
      //将【零亿】换成【亿】【零万】换成【万】
      result = result.replace(/零亿/g, "亿").replace(/零万/g, "万");
      //将【亿万】换成【亿】
      result = result.replace(/亿万/g, "亿");
      //移除末尾的零
      result = result.replace(/零+$/, "");
      //将【零一十】换成【零十】
      //result = result.replace(/零一十/g, '零十');//貌似正规读法是零一十
      //将【一十】换成【十】
      result = result.replace(/^一十/g, "十");
      return result;
    },
  },
};
</script>
<style lang="less" scoped>
.search-bar {
  padding-bottom: 10px;
  text-align: left;
  .label {
    padding: 0 20px;
  }
  .label::before {
    content: "*";
    color: #f56c6c;
    margin-right: 4px;
  }
  .search-btn {
    margin-left: 20px;
  }
}
.el-table {
  border: 1px solid #000;
}
/deep/ .el-table tr th {
  background-color: rgb(184, 183, 218);
}
</style>